class CacheStorage {
	storage: Storage

	constructor(isLocal: boolean) {
		this.storage = isLocal ? localStorage : sessionStorage
	}

	setItem(key: string, value: any) {
		if (value) {
			this.storage.setItem(key, JSON.stringify(value))
		}
	}

	getItem(key: string): any {
		let value = this.storage.getItem(key)
		if (value) {
			value = JSON.parse(value)
			return value
		}
	}

	removeItem(key: string) {
		this.storage.removeItem(key)
	}

	clear() {
		this.storage.clear()
	}

	key(index: number) {
		this.storage.key(index)
	}

	length(): number {
		return this.storage.length
	}
}

const localCache = new CacheStorage(true)
const sessionCache = new CacheStorage(false)

// 清空多个指定缓存数据
export function clearSessionCaches(names: string[]): void {
	for (const name of names) {
		sessionCache.removeItem(name)
	}
}
export function clearLocalCaches(names: string[]) {
	for (const name of names) {
		localCache.removeItem(name)
	}
}

export { localCache, sessionCache }
